// index.js
const { Toast, Dialog } = require("../../../config/modal")
const utils = require("../../../utils/util")
const config = require("../../../config/config")
const { LOGIN, LOCATION } = require("../../../config/login.js")
// 获取应用实例
const App = getApp()
Page({
    data: {
        system: {
            logo: config.logo
        },
        isStartMp: App.$isStartMp(), // 是否显示公众号图片
        publicImg: 'http://aliyun.thisforyou.cn:9004/cbd-prod/mini/public2.jpg',
        showQrCodeDialog: false,
        showShare: false,
        showScan: false,
        showOverlay: false,
        activityImg: "http://aliyun.thisforyou.cn:9004/cbd-prod/gift/gift.png?v=" + new Date().getTime(),
        tbkImg: '',
        options: [
            { name: '微信', icon: 'wechat', openType: 'share' },
            { name: '微博', icon: 'weibo' },
            { name: '复制链接', icon: 'link' },
            { name: '分享海报', icon: 'poster' },
            { name: '二维码', icon: 'qrcode' },
        ],

        // 是否授权地理位置
        isAuthLocation: App.$isAuthLocation(),

        //  是否授权
        isAuth: App.$isAuth(),

        // 系统设备的一些宽高参数
        window: {},

        // 主题颜色
        theamTextColor: App.globalData.theamTextColor,

        // 轮播
        swiperImgs: [],

        // 通知条
        notice: {
            text: "在代码阅读过程中人们说脏话的频率是衡量代码质量的唯一标准。"
        },
        // 用户信息
        userInfo: {
            province: "请先授权",
            school: '',
            avatar: '',
            invitees: '',
        },
        actionFunctions: [
            {
                image: "/static/function/task.png",
                text: "找人帮忙",
                page: "otherTaskPage",
                open: true,
            },
            {
                image: "/static/function/package.png",
                text: "找人拿快递",
                page: "packagesPage",
                open: true,
            },
            {
                image: "/static/function/zahuo.png",
                text: "转让二手",
                page: "addProduct",
                open: true,
            },
            {
                image: "/static/tabar-icon/tai-selected.png",
                text: "发布动态",
                page: "dynamic",
                open: true,
            },
            {
                image: "/static/function/recruit.png",
                text: "发布兼职信息",
                page: "addRecruit",
                open: true,
            }
        ],
        // 功能列表
        functions: [
             {
                image: "/static/function/tuodan.png",
                text: "我想脱单",
                page: "tuodan",
                open: true,
                auth: true,
            },
            {
                image: "/static/function/recruit.png",
                text: "兼职信息",
                page: "recruit",
                open: true,
                auth: false,
            },

            {
                image: "/static/function/task.png",
                text: "任务中心",
                page: "taskCenter",
                open: true,
                auth: false,
            },
             {
                image: "/static/function/zahuo.png",
                text: "二手物品",
                page: "product",
                open: true,
                auth: false,
            },

            ],
        inviteCode: '',
        currentDate: '2021年 牛年大吉',
        obj: {
            0: {
                list: ["l", "w"],
            },
            1: {
                list: [1, 2]
            }
        },

        rollRecords: [],
        notice: "",
        activityBoolean: true,
        startDongTai: false,
        // 热单推荐
        swiperHotList: [],
        product: []
    },
    page: {
        authPage: "/pages/noAuth/index",
        userInfoEdit: "/pages/tabbar/user/userInfoEdit/index",
        userInfoCenter: "/pages/tabbar/user/userInfoCenter/index",
        schoolPage: "/pages/school/index",
        otherTaskPage: "/pages/tabbar/index/task/other/index",
        packagesPage: '/pages/tabbar/index/task/packages/index',
        dynamic: '/pages/tabbar/dynamic/pushArticle/index',
        taskPush: "/pages/tabbar/user/userInfoCenter/myTask/index",
        packagePush: "/pages/tabbar/user/userInfoCenter/myPackages/index",
        taskCenter: "/pages/tabbar/index/robOrders/index",
        concat: '/pages/concat-me/index',
        recruit: '/pages/recruit/index',
        sharePage: '/pages/invite/index',
        invite: '/pages/invite/index',
        product: '/pages/tabbar/index/product/index',
        addProduct: '/pages/tabbar/user/userInfoCenter/myProduct/add/index',
        addRecruit: '/pages/recruit/add/index',
        tuodan: "/pages/tuodan/index",
        orderDetail: '/pages/tabbar/index/robOrders/share/index',
        productDetail: "/pages/tabbar/index/product/detail/index"
    },
    URL: {
        getProduct: '/product/pageList',
        getSwiper: "/common/getSwiper",
        getRollRecords: "/integral/getRollRecords",
        indexNotice: "/common/indexNotice",
        // 是否开活动
        activityBoolean: "/common/activityBoolean",
        updateInvitees: "/customer/updateInvitees",
        createPosters: "/customer/createPosters",
        getNewestTask: '/task/getNewestTask'
    },
    showPublicImg() {
        let imgUrl = this.data.publicImg + "?v=" + new Date().getTime();
        let imgUrls = [imgUrl];
        wx.previewImage({
            current: imgUrl,
            urls: imgUrls
        })
    },
    initNotice() {
        App.$get(false, this.URL.indexNotice, {}, res => {
            if (res.R) {
                this.setData({
                    notice: res.data
                })
            }
        })
    },
    // 获取两个任务单子
    getSwiperHotList() {
        App.$get(false, this.URL.getNewestTask, { schoolName: this.data.userInfo.school }, res => {
            if (res.R) {
                this.setData({
                    swiperHotList: res.data
                })
            }
        })
    },

    // 获取校园二手闲置
    getProduct() {
        App.$get(false, this.URL.getProduct, { pageSize: 10, schoolName: this.data.userInfo.school }, res => {
            if (res.R) {
                let rows = res.data.rows;
                this.setData({
                    product: rows
                })
            }
        })
    },
    toOrdertList() {
        App.$navigateTo(this.page.taskCenter, false)
    },
    toProductList() {
        App.$navigateTo(this.page.product, false)
    },
    toDetailProduct(e) {
        let item = utils.getEvent(e).item;
        App.$navigateTo(this.page.productDetail + "?productNo=" + item.productNo, false)
    },

    toOrderDetail(e) {
        let type = utils.getEvent(e).type;
        let taskNo = utils.getEvent(e).taskno;
        let params = '?taskNo=' + taskNo + '&type=' + type;
        App.$navigateTo(this.page.orderDetail + params, false)
    },

    // 弹出图片点击进入活动页面
    toDetailActivity() {
        App.$navigateTo(this.page.invite, false)
    },
    // 检查弹框内容
    checkShowActivityTime() {
        if (!this.data.activityBoolean) {
            return;
        }
        let currentTime = new Date().getTime();
        let time = App.$getData('showActivityTime');
        if (utils.isInvalid(time)) {
            App.$saveData('showActivityTime', currentTime);
            setTimeout(() => {
                this.setData({
                    showOverlay: true,
                })
            }, 1000)
        } else {
            if (currentTime - time >= 30 * 60 * 1000) {
                App.$saveData('showActivityTime', currentTime);
                this.setData({
                    showOverlay: true,
                })
            }
        }
    },
    onClickHide() {
        this.setData({
            showOverlay: false,
        })
    },
    onLoad(options) {
        this.setData({
            window: App.globalData.window,
            'currentDate': utils.getYmd_Week(),
        })
        // 检查是否被邀请进来的
        App.$handlerInviteCode(options);

        // 通知
        this.initNotice();


        // 初始化轮播图
        this.initSwipers();

        // 读取滚动提现用户
        this.getRollRecords();

        // 是否开启活动
        this.activityBoolean();



    }

    // 获取提现列表
    , getRollRecords() {
        App.$get(false, this.URL.getRollRecords, { pageSize: 50 }, res => {
            if (res.R) {
                this.setData({
                    'rollRecords': res.data.rows
                })
            }
        })
    }

    // 是否开启邀请有礼活动
    , activityBoolean() {
        App.$get(false, this.URL.activityBoolean, {}, res => {
            if (res.R) {
                this.setData({
                    activityBoolean: res.data.start
                })
            }
        })
    }

    , onShow() {
        // wx.requestPayment({
        //     timeStamp: '1632381675',
        //     nonceStr: '516fde466b96408889af7c6c93e6f9d9',
        //     package: 'prepay_id=wx231521157130048422bbaefd631f760000',
        //     signType: 'RSA',
        //     paySign: 'AK5sKkEjrZB8aqM7ha+VHFczHR93mWszVH+/kq/3iMuZ+SZSW1gghtCDlbFydHoqo11u9hM3kSjGX+zoEx/oJm21fap3vNTur45uy2wgGMuvji6K1U6QIKYA2Pppz+3eKQ56HYv6N128eSSqaEsAW6m3yrcXmc1zJDFfSbHB49UXLWXbnS7NJQTeYdkPwm9vrCAsL+rHzF50G4WDr70cSSLN1CLOAjjOOr7K6royO6Xoqb/DXLyOYbXVEABtBGGQ97awUhnyUx/gukhthaxB7HaLeh4s1q6RequXRuCMpJDnBlxtLghLXnP/yXrcLyyowGIVHSwSGFnEFAEnxEA/Nw==',
        //     success (res) { },
        //     fail (res) { }
        //   })
        this.initUserInfo();
        this.updateInvitees();
        this.checkShowActivityTime();

        let that = this;
        setTimeout(() => {
            that.setData({
                startDongTai: App.$getActionFlag(),
                isStartMp: App.$isStartMp(),
                ['functions[1].open']: App.$getActionFlag()
            })
        }, 200)



        this.getSwiperHotList();

        this.getProduct();
    },


    // 生成海报
    createPosters() {
        let that = this;
        App.$post(true, this.URL.createPosters, {}, res => {
            if (res.R) {
                let poster = res.data
                var aa = wx.getFileSystemManager();
                aa.writeFile({
                    filePath: wx.env.USER_DATA_PATH + '/poster.jpg',
                    data: poster.slice(22),
                    encoding: 'base64',
                    success: res => {
                        wx.saveImageToPhotosAlbum({
                            filePath: wx.env.USER_DATA_PATH + '/poster.jpg',
                            success: function (res) {
                                that.setData({
                                    showQrCodeDialog: false
                                })
                                App.$alert('海报已保存到相册中')
                            },
                            fail: function (err) {
                                that.setData({
                                    showQrCodeDialog: false
                                })
                                App.$alert('海报已保存失败')
                            }
                        })
                        console.log(res)
                    }, fail: err => {
                        that.setData({
                            showQrCodeDialog: false
                        })
                        App.$alert('海报已保存失败,请检查是否已经相册授权')
                        console.log(err)
                    }
                })
            }
        })
    },

    // 更新邀请人
    updateInvitees() {
        let invitees = App.$getData('invitees');
        if (!utils.isInvalid(invitees) && App.$isAuth()) {
            // 更新
            App.$postIsTip(false, false, this.URL.updateInvitees, { invitees: invitees }, res => {
                console.log("更新邀请人", invitees, res.msg)
                if (res.R) {
                    this.updateLocalStoreInfo(invitees);
                    App.$removeStore('invitees');
                }
            })
        }
    },

    // 初始化轮播图
    initSwipers() {
        App.$get(true, this.URL.getSwiper, {}, res => {
            this.setData({
                'swiperImgs': res.data
            })
        })
    },

    // 点击左上角头像
    clickAvatar(e) {
        if (!App.$isAuth()) {
            App.$navigateToAuth()
            return;
        }
        let imgUrl = e.currentTarget.dataset.img;
        let imgUrls = [imgUrl];
        wx.previewImage({
            current: imgUrl,
            urls: imgUrls
        })
    },

    // 选择完善信息
    toPerfectInfo() {
        App.$navigateTo(this.page.userInfoEdit, true);
    },


    // 点击授权地理位置
    toAuthLocation() {
        LOCATION.toAuthLocation((res) => {
            this.initUserInfo();
        })
    },
    // 点击功能模块
    toJumFunctionPage(e) {
        let isOpen = e.currentTarget.dataset.open;
        if (isOpen) {
            let page = e.currentTarget.dataset.page;

            if (!this.data.activityBoolean && page == "sharePage") {
                Toast.fail('邀请有奖活动已结束～')
                return;
            }

            App.$navigateTo(this.page[page], e.currentTarget.dataset.auth);
            return;
        }
        Toast.fail('开发君，💪开发中，尽请期待!!!!')
    },
    actionJump(e) {
        let isOpen = e.currentTarget.dataset.open;
        if (isOpen) {
            let page = e.currentTarget.dataset.page;
            this.setData({
                'showShare': false
            })

            if (App.$isAuth()) {
                let schoolName = App.$getUserInfo().schoolName;
                if (utils.isInvalid(schoolName)) {
                    App.$alertConfirm({
                        msg: '发布信息需要先填写联系方式,以便他人联系你哟～',
                        success: function () {
                            App.$navigateTo('/pages/tabbar/user/userInfoEdit/index', true);
                        }
                    })
                    return;
                }
                App.$navigateTo(this.page[page], true);
            } else {
                App.$navigateTo('/pages/noAuth/index?nextPage=http', false);
            }
            return;
        }
        Toast.fail('开发君，💪开发中，尽请期待!!!!')
    },
    onClosePopup() {
        this.setData({
            'showShare': false
        })
    },
    // 初始化用户信息
    initUserInfo() {
        let userInfo = App.$getUserInfo();
        if (!utils.isInvalid(userInfo)) {
            this.setData({
                "userInfo.province": utils.isInvalid(userInfo.citySure) ? "请先授权" : (userInfo.provinceSure + " " + userInfo.citySure),
                "userInfo.avatar": userInfo.avatar,
                "userInfo.school": userInfo['schoolName'],
                "userInfo.inviteCode": userInfo['inviteCode'],
                "userInfo.nickName": userInfo.nickName,
                "userInfo.userCode": userInfo['userCode'],
                "userInfo.inviteQrCode": userInfo['inviteQrCode'],
                "userInfo.invitees": utils.isInvalid(userInfo['invitees']) ? '' : userInfo['invitees'],
            })
        }
        this.setData({
            isAuthLocation: App.$isAuthLocation(),
            isAuth: App.$isAuth()
        })
    },
    intoTaskCenter() {
        App.$navigateTo(
            this.page.taskCenter
            , false)
    },
    btnConcatClick() {
        App.$navigateTo(
            this.page.concat
            , false)
    },
    clickAddPlus() {
        this.setData({
            'showShare': true,
            publicImg: this.data.publicImg + "?v=" + new Date().getTime()
        })

    },
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
        wx.stopPullDownRefresh();
    }
    , onShareAppMessage() {
        return App.$onShare('/pages/tabbar/index/index', null, "校园CBD")
    },

    getInviteCode() {
        this.setData({
            showQrCodeDialog: true,
        })
    },

    scanInviteCode() {
        let _this = this;
        let userInfo = App.$getUserInfo()
        if (!utils.isInvalid(userInfo.invitees)) {
            App.$alert("您已有邀请人")
            return;
        }

        Toast.loading({
            message: "解析中...",
            mask: true,
            duration: 60000
        })

        wx.scanCode({
            onlyFromCamera: false,
            scanType: ['qrCode'],
            success(res) {
                if (res.scanType != 'QR_CODE') {
                    Toast.fail("未检测到到二维码")
                    return;
                }

                let detail = res.result
                Toast.clear({})
                if (utils.isInvalid(detail) || detail.length != 6) {
                    Toast.fail("邀请码不合法")
                    return;
                }

                // 更新邀请人
                App.$post(true, _this.URL.updateInvitees, { invitees: detail }, res => {
                    console.log("更新邀请人", detail, res.msg)
                    if (res.R) {
                        Toast('邀请成功～')

                        _this.updateLocalStoreInfo(detail);

                        _this.closeScanDialog();

                        setTimeout(() => {
                            if (utils.isInvalid(userInfo.userPhone)) {
                                App.$saveData('invitees', detail)
                                App.$navigateTo(_this.page.userInfoEdit, true);
                            }
                        }, 500)
                    }
                })
            },
            fail(e) {
                Toast.clear({})
            }
        })
    },

    updateLocalStoreInfo(invitees) {
        let userInfo = App.$getUserInfo();
        userInfo.invitees = invitees;
        App.$saveUserInfo(userInfo);
        this.setData({
            'userInfo.invitees': invitees
        })
    },


    // 弹出二维码
    showQrCodeDialog() {
        if (!App.$isAuth()) {
            App.$navigateToAuth();
            return;
        }
        this.getInviteCode();
    },
    closeScanDialog() {
        this.setData({
            showScan: false
        })
    },
    showScanDialog() {
        if (!App.$isAuth()) {
            App.$navigateToAuth();
            return;
        }
        this.setData({
            showScan: true
        })
    }
    , showLagerImg(e) {
        let imgUrl = e.currentTarget.dataset.img;
        let imgUrls = [imgUrl];
        wx.previewImage({
            current: imgUrl,
            urls: imgUrls
        })
    },
    toJumpTbk() {
        App.$navigateTo(this.page.tbkPage, false)
    }

})

